var pageNum = 0;
var drawLocked = false;
var docObject;
var wisId = "";
var userid = "";
var userName = "";
var classid = "";
var topic_msg = "";
var topic_stu_to_teacher = "";
var topic_teacher_to_stu = "";
var online_count = 0;
var handerStuid = "";
var handerStuname = "";
var dmsPubKey = "";
var dmsSubKey = "";
var rtmp_publish_url = "";
var rtmp_play_url = "";
var hls_play_url = "";
var lssapp_id = "";
var stream_tea = "";
var stream_stu = "";
var lss;
var play_status = 0;
var hand_status = 0;
var objectPlayer;

function GetQueryString(param) {
	var request = {
		QueryString: function (val) {
			var uri = window.location.search;
			var re = new RegExp("" + val + "=([^&?]*)", "ig");
			return ((uri.match(re)) ? (decodeURI(uri.match(re)[0]
				.substr(val.length + 1))) : '');
		}
	};
	return request.QueryString(param);
}

/*
 * 初始化参数
 */
function initParam() {
	wisId = GetQueryString("wisid");
	userid = GetQueryString("userid");
	userName = GetQueryString("name");
	classid = GetQueryString("classid");
	topic_msg = GetQueryString("topic");
	topic_stu_to_teacher = GetQueryString("topic") + "_to_teacher";
	topic_teacher_to_stu = GetQueryString("topic") + "_to_stu";
	lssapp_id = GetQueryString("lssapp_id");
	stream_tea = GetQueryString("stream_tea");
	stream_stu = GetQueryString("stream_stu");
	if (userName == null || userName.length == 0)
		userName = "匿名";
}

function initUrl(data) {
	rtmp_publish_url = data.rtmp_publish_url;
	rtmp_play_url = data.rtmp_play_url;
	hls_play_url = data.hls_play_url;
	dmsPubKey = data.dmsPubKey;
	dmsSubKey = data.dmsSubKey;
}

function u_c(c, u) {
	if (!c || !u) {
		window.location.href = "paramerror.html";
		return;
	}
	$.ajax({
		type: "POST",
		timeout: 8000,
		url: "./remoteinvoke.php",
		dataType: "json",
		data: {
			method: 'u_c',
			classid: c,
			userid: u
		},
		success: function (data) {
			if (data.Flag == 100) {
				if (data.Info && data.Info.result) {
					initUrl(data);
					initWis();
					initDms();
					initTool();
					initPlay();
				} else {
					window.location.href = "nopower.html";
					return;
				}
			} else {
				window.location.href = "apierror1.html";
				return;
			}
		},
		error: function (error) {
			window.location.href = "apierror2.html";
			return;
		}
	});
}

function u_c_c(c, u) {
	if (!c || !u) {
		window.location.href = "paramerror.html";
		return;
	}
	$.ajax({
		type: "POST",
		timeout: 8000,
		url: "./remoteinvoke.php",
		dataType: "json",
		data: {
			method: 'u_c',
			classid: c,
			userid: u
		},
		success: function (data) {
			if (data.Flag == 100) {
				if (data.Info && data.Info.result) {

				} else {
					window.location.href = "nopower.html";
					return;
				}
			} else {
				window.location.href = "apierror1.html";
				return;
			}
		},
		error: function (error) {
			window.location.href = "apierror2.html";
			return;
		}
	});
}

/**
 * 初始化白板
 */
function initWis() {
	var api = WISAPI.New('./interface.php');
	WIS.Init({
		wisId: wisId,
		api: api,
		userid_: userid,
		container: 'wis_context_inner',
		width: 0,
		height: 0,
		success: function () {
			WIS.Color("#FF8C00");
			WIS.AllowDraw({
				ballow: false
			});
		},
		failure: function (err) {
			console.log("init fail:  " + JSON.stringify(err));
			alert("加载课件文档失败，请刷新页面重新加载");
		},
		updateUser: function (total, data_) {
			$(".rightLabel span").html(total);
			online_count = total;
		},
		onConnect: function () {
		},
		onReconnect: function () {

		},
		onConnectClose: function () {

		},
		onDocLoad: function (info) {
			console.log("docObject:" + JSON.stringify(info));
			docObject = info;
			if (!!docObject) {
				$("#docList div[docId=" + docObject["id"] + "]").addClass(
					"selectDoc");
				$("#docList div[docId=" + docObject["id"] + "]").siblings()
					.removeClass("selectDoc");
			}
		},
		onPageChange: function (page, total) {
			pageNum = total;
			$("#pageList").html("");
			for (var i = 1; i <= total; i++) {
				var option = $("<option>").val(i).text(i);
				$("#pageList").append(option);
			}
			$("#pageList").val(page);
		}
	});
}


/** **************DMS相关**************** */
function AddMessage(name, msg, style) {
	var faceMsg = msg;
	for (var item in faceMap) {
		faceMsg = faceMsg.replace(new RegExp("\\" + item, "g"),
			"<img src='images/faces/" + faceMap[item] + ".gif'/>");
	}
	var msgHtml = "<div><span class='" + style + "' >" + name + "：</span>"
		+ faceMsg + "</div>";
	$("#messageBox").html($("#messageBox").html() + msgHtml);
	$("#messageBox").scrollTop(
		document.getElementById("messageBox").scrollHeight);
}

function Publish() {
	var send = $("#msgSendTxt").val();
	if (send == "")
		return;
	send = jQuery('<div />').text(send).html();
	ROP.Publish('{  "name":"' + userName + '", "message": "' + send + '"}',
		topic_msg);
	$("#msgSendTxt").val("");
}

function initDms() {
	ROP.On("enter_suc", function () {
		AddMessage("系统消息", "连接成功", "sysSpan");
		pubStuEnterMsg();
	});
	ROP.On("reconnect", function () {
		AddMessage("系统消息", "重新连接", "sysSpan");
	});
	ROP.On("offline", function (err) {
		AddMessage("系统消息", "连接已断开", "sysSpan");
		window.location.href = "doulogin.html";
		return;
	});
	ROP.On("enter_fail", function (err) {
		AddMessage("系统消息", "连接失败", "sysSpan");
	});
	ROP.On("losed", function () {
		AddMessage("系统消息", "连接已丢失", "sysSpan");
	});
	ROP.On("publish_data", function (data, topic) {
		var d = eval('(' + data + ')');
		if (topic == topic_msg) {
			var msg = d["message"];
			if (msg != null) {
				AddMessage((!!d["name"]) ? d["name"] : "匿名", msg);
			}
		}

		if (topic == topic_teacher_to_stu) {
			handleCtrlMsg(d);
		}

	});

	ROP.Enter(dmsPubKey, dmsSubKey, classid + "_" + userid);
	ROP.Subscribe(topic_msg);
	ROP.Subscribe(topic_teacher_to_stu);
	document.onkeydown = function (e) {
		if (e == null || e.keyCode == null || e.ctrlKey == null)
			return;
		if (e.keyCode == 13 && e.ctrlKey) {
			document.getElementById("msgSendTxt").value += "\n";
		} else if (e.keyCode == 13) {
			e.preventDefault();
			Publish();
		}
	};
}

var getCount = 0;
function pubStuEnterMsg() {
	if (getCount > 10) {
		return;
	}
	if (!WIS.getClientid()) {
		getCount++;
		setTimeout(function () {
			pubStuEnterMsg();
		}, 500);
		return;
	}
	ROP.Publish('{"name":"' + userName + '", "userid": "' + userid + '","clientid":"' + WIS.getClientid() + '","oper":"enter"}', topic_stu_to_teacher);
	return;
}

function callbackplay() {
	jwplayer(player).play(true);
}
var position = -1;
function callbackseek() {
	if (position != -1) {
		jwplayer(player).seek(parseInt(position));
		position = -1;
	}
}

function handleCtrlMsg(ctrlMsg) {
	if (ctrlMsg['oper'] == 'refresh') {
		ROP.Publish('{"name":"' + userName + '", "userid": "' + userid + '","clientid":"' + WIS.getClientid() + '","oper":"enter"}', topic_stu_to_teacher);
	}
	if (ctrlMsg["oper"] == "canhand") {
		$("#canhand").attr("class", "offMicBtn");
	}
	if (ctrlMsg["oper"] == "cannothand") {
		$("#canhand").attr("class", "offHandBtn");
	}
	if (ctrlMsg["oper"] == "puthand") {
		handerStuname = ctrlMsg["name"];
		handerStuid = ctrlMsg["userid"];
		if (userid == ctrlMsg["userid"]) {
			closeStuPlayHtml();
			openStuPublishHtml();
		} else {
			closeStuPublishHtml();
			openStuPlayHtml();
		}
	}
	if (ctrlMsg["oper"] == "closeStuPlay") {
		closeStuPublishHtml();
		closeStuPlayHtml();
	}
	if (ctrlMsg["oper"] == "loadmp3") {
		var file = ctrlMsg["file"];
		loadMp3Player(file, null, null);
	}
	if (ctrlMsg["oper"] == "mp3play") {
		var file = ctrlMsg["file"];
		position = ctrlMsg["position"];
		if (!jwplayer(player).getPlaylist() || jwplayer(player).getPlaylist() < 1) {
			loadMp3Player(file, callbackplay, callbackseek);
			return;
		}
		var curfile = jwplayer(player).getPlaylistItem(0).file;
		if (curfile != file) {
			loadMp3Player(file, callbackplay, callbackseek);
		} else {
			jwplayer(player).play(true);
			position = -1;
		}
	}
	if (ctrlMsg["oper"] == "mp3pause") {
		jwplayer(player).pause(true);
	}
	if (ctrlMsg["oper"] == "mp3mute") {
		jwplayer(player).setMute(ctrlMsg["mute"]);
	}
	if (ctrlMsg["oper"] == "mp3seek") {
		console.log("offset:" + ctrlMsg["offset"]);
		jwplayer(player).seek(parseInt(ctrlMsg["offset"]));
	}
}

function openStuPlayHtml() {
	$("#vadioPlay").show();
	$("#stuinfo").html(handerStuname + "正在视频");
	$("#stuPlay").attr(
		"src",
		"stu_play.html?lssapp_id=" + lssapp_id + "&stream_stu="
		+ stream_stu);
}

function closeStuPlayHtml() {
	try {
		$(window.parent.document).contents().find("#stuPlay")[0].contentWindow
			.closeme();
	} catch (err) {
	}
	$("#stuPlay").attr("src", "");
	$("#vadioPlay").hide();
}

function openStuPublishHtml() {
	$("#vadioPublish").show();
	$("#stupublish").show();
	$("#stuinfo_publish").html(handerStuname + "正在视频");
	$("#stuPublish").attr("src", "stu_publish.html?lssapp_id=" + lssapp_id + "&stream_stu=" + stream_stu + "&v=1.0");
}

function closeStuPublishHtml() {
	try {
		$("#stupublish").html("上麦");
		$("#stupubset").show();
		$(window.parent.document).contents().find("#stuPublish")[0].contentWindow.closeme();
	} catch (err) { }
	$("#stuPublish").attr("src", "");
	$("#vadioPublish").hide();
}

function canvasSupport() {
	return !!document.createElement('canvas').getContext;
}

function handme() {
	var btnClass = $("#canhand").attr("class");
	if (btnClass == "offHandBtn") return;
	$("#canhand").attr("class", "offHandBtn");
	ROP.Publish('{"name":"' + userName + '", "userid": "' + userid + '","oper":"stuhand"}', topic_stu_to_teacher);
}

function publishme() {
	var opername = $("#stupublish").html();
	if (opername == "上麦") {
		$(window.parent.document).contents().find("#stuPublish")[0].contentWindow.publishme();
		$("#stupublish").html("下麦");
		$("#stupubset").hide();
	} else {
		$("#stupublish").html("上麦");
		$("#stupubset").show();
		$(window.parent.document).contents().find("#stuPublish")[0].contentWindow.closeme();
	}

}

function stupubset() {
	var stuframe = $(window.parent.document).contents().find("#stuPublish")[0].contentWindow;
	var micArray = stuframe.getMics();
	var camArray = stuframe.getCams();
	if (!micArray || !camArray) {
		alert("暂未获取到设备，请稍后设置");
		return;
	}
	$("#selmic option").remove();
	$("#selcam option").remove();
	var selmic = stuframe.getStumic();
	var selcam = stuframe.getStucam();
	for (var i = 0; i < 5; i++) {
		if (micArray[i]) {
			if (i == selmic) {
				$("#selmic").append("<option value=" + i + " selected>" + micArray[i] + "</option>");
			} else {
				$("#selmic").append("<option value=" + i + ">" + micArray[i] + "</option>");
			}
		}
		if (camArray[i]) {
			if (i == selcam) {
				$("#selcam").append("<option value=" + i + " selected>" + camArray[i] + "</option>");
			} else {
				$("#selcam").append("<option value=" + i + ">" + camArray[i] + "</option>");
			}
		}
	}
	$('#mysetModal').reveal();
}

function initTool() {
	$(".toolList .toolItem").live("click", function () {
		if ($(this).attr("id") == "largeTool") {
			var cur_width = $("#wis_context").width();
			var des_width = cur_width + 50;
			var screenwidth = window.screen.width;
			var limitwidth = screenwidth - 76 - 10 - 280;
			if (des_width > limitwidth) return;
			WIS.Resize(des_width, 0);
		} else if ($(this).attr("id") == "smallTool") {
			var cur_width = $("#wis_context").width();
			var des_width = cur_width - 50;
			if (des_width < 300) return;
			WIS.Resize(des_width, 0);
		}
	});

}

function genK(option) {
	if (!classid) {
		alert(lang_msg['notinit'][lang]);
		return;
	}
	$.ajax({
		type: "POST",
		timeout: 8000,
		url: "./remoteinvoke.php",
		dataType: "json",
		data: {
			method: 'genK',
			appid: option.appid,
			stream: option.stream
		},
		success: function (data) {
			if (data.Flag == 100) {
				if (option.success)
					option.success(data);
			} else {
				if (option.failure)
					option.failure(data.FlagString);
			}
		},
		error: option.failure
	});
}

function initPlay() {

	var stream_tea_tmp = stream_tea.replace(/-/g, '_');
	genK({
		appid: lssapp_id,
		stream: stream_tea_tmp,
		success: function (data) {
			console.log(data);
			//判断手机还是pc
			var userAgentInfo = navigator.userAgent;
			var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
			var isPc = true;
			for (var v = 0; v < Agents.length; v++) {
				if (userAgentInfo.indexOf(Agents[v]) > 0) {
					isPc = false;
					break;
				}
			}
			if (isPc) {

				objectPlayer = new aodianPlayer({
					container: 'playerView',// 播放器容器ID，必要参数
					rtmpUrl: rtmp_play_url + '/' + lssapp_id + '/' + stream_tea_tmp + '?k=' + data.k + '&t=' + data.t,// 控制台开通的APP
					// rtmp地址，必要参数
					hlsUrl: hls_play_url + '/' + lssapp_id + '/' + stream_tea_tmp + '.m3u8' + '?k=' + data.k + '&t=' + data.t,// 控制台开通的APP
					// hls地址，必要参数

					width: '278',// 播放器宽度，可用数字、百分比等
					height: '180',// 播放器高度，可用数字、百分比等
					autostart: true,// 是否自动播放，默认为false
					bufferlength: '1',// 视频缓冲时间，默认为3秒。hls不支持！手机端不支持
					maxbufferlength: '2',// 最大视频缓冲时间，默认为2秒。hls不支持！手机端不支持
					stretching: '1',// 设置全屏模式,1代表按比例撑满至全屏,2代表铺满全屏,3代表视频原始大小,默认值为1。hls初始设置不支持，手机端不支持
					controlbardisplay: 'disable',// 是否显示控制栏，值为：disable、enable默认为disable。
					adveDeAddr: 'images/yt_02.png',
					adveWidth: 278,
					adveHeight: 130,
					adveReAddr: 'http://www.ykyueke.com'
				});
			} else {

				var thHlsPlay = hls_play_url + '/' + lssapp_id + '/' + stream_tea_tmp + '.m3u8' + '?k=' + data.k + '&t=' + data.t;
				var html = '<video src="' + (thHlsPlay) + '" controls="controls" autoplay="autoplay" poster webkit-playsinline >您的浏览器不支持 video 标签。</video>';
				$("#playerView").html(html);
				$("#playerView video")[0].play();
			}
		},
		failure: function (errStr) {
			alert(errStr.responseText);
		}
	});

	if (!canvasSupport()) {
		$(".switchBtn").hide();
	}

	$("#selme").click(function () {
		if ($(this).is(':checked')) {
			setCookie("noprompt", "1", 365);
		} else {
			setCookie("noprompt", "2", 365);
		}
	});
}

var player = "mp3player_stu";

function loadMp3Player(mp3file, callback_p, callback_s) {
	var playerInstance = jwplayer(player);
	playerInstance.setup({
		file: mp3file,
		height: 30,
		width: "100%",
		events: {
			onReady: function () {
				jwplayer(player).setVolume(100);
				setMplay3Carver();
				if (callback_p) callback_p();
			},
			onPlay: function () {
				if (callback_s) callback_s();
			}
		}
	});
}

function setMplay3Carver() {
	var top = $(window).scrollTop();
	$("#mp3player_stu_carver").css("top", $("#mp3player_stu").offset().top - top);
	$("#mp3player_stu_carver").css("left", $("#mp3player_stu").offset().left);
	$("#mp3player_stu_carver").width($("#mp3player_stu").width());
	$("#mp3player_stu_carver").height($("#mp3player_stu").height());
}

var scrolltimer1;
$(function () {
	initParam();
	u_c(classid, userid);
	var interv = self.setInterval(function () {
		u_c_c(classid, userid);
	}, 60000);
	$(window).scroll(function () {
		if (scrolltimer1) clearInterval(scrolltimer1);
		var top = $(window).scrollTop();
		if (top < 64) top = 64;
		scrolltimer1 = setInterval(function () {
			$(".toolsBar").animate({ top: top + "px" }, 300);
			$(".rightBox").animate({ top: top + "px" }, 300);
			setMplay3Carver();
		}, 1000);
	});
	$(".stuoper").toggle(function () {
		$(".stuView .displayBox").animate({ height: 'toggle', opacity: 'toggle' }, "slow");
		if (!$("#vadioPlay").is(':hidden')) {
			$("#vadioPlay").animate({ height: "50px" }, 500);
			$("#stuoper_play").html("开");
		}
		if (!$("#vadioPublish").is(':hidden')) {
			$("#vadioPublish").animate({ height: "50px" }, 500);
			$("#stuoper_pub").html("开");
		}

	}, function () {
		$(".stuView .displayBox").animate({ height: 'toggle', opacity: 'toggle' }, "slow");
		if (!$("#vadioPlay").is(':hidden')) {
			$("#vadioPlay").animate({ height: "230px" }, 500);
			$("#stuoper_play").html("收");
		}
		if (!$("#vadioPublish").is(':hidden')) {
			$("#vadioPublish").animate({ height: "230px" }, 500);
			$("#stuoper_pub").html("收");
		}
		$(".stuoper").html("收");
	});

	$("#setok").live("click", function () {
		$(window.parent.document).contents().find("#stuPublish")[0].contentWindow.setStumic($("#selmic").val());
		$(window.parent.document).contents().find("#stuPublish")[0].contentWindow.setStucam($("#selcam").val());
		setCookie("stu_selmic", $("#selmic").val(), 365);
		setCookie("stu_selcam", $("#selcam").val(), 365);
		$("#mysetModal").trigger('reveal:close');
	});
});
